<template>
    <el-dialog
        class="withdraw-audit-dialog"
        title="审核"
        v-model="dialogVisible"
        width="60%"
        :align-center="true"
        @close="closedCallback">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="auto">
            <h1>提现信息</h1>
            <el-form-item label="提现编号：">{{ form.sn || '-' }}</el-form-item>
            <el-form-item label="昵称："> {{ form.nickName || '-' }}</el-form-item>
            <el-form-item label="姓名："> {{ form.realName || '-' }}</el-form-item>
            <el-form-item label="手机号："> {{ form.mobile || '-' }}</el-form-item>
            <!-- todo:身份证号 -->
            <el-form-item label="身份证号：">{{ form.idNo || '-' }}</el-form-item>
            <!-- todo:身份证号 -->
            <el-form-item label="提现金额："> {{ form.amount ? `¥ ${form.amount / 100}` : '-' }}</el-form-item>
            <el-form-item label="提现至：">{{ form.withdrawToName || '-' }}</el-form-item>
            <el-form-item label="银行卡信息：">
                <template v-if="form.withdrawTo == 1"> - </template>
                <template v-else> {{ form.bankName }} ({{ form.bankAccountNo }}) </template>
            </el-form-item>
            <el-form-item label="申请时间：">{{ form.createdAt || '-' }}</el-form-item>
            <h1>审核信息</h1>
            <el-form-item label="审核状态：">{{ form.auditStatusName || '-' }}</el-form-item>
            <el-form-item label="审核结果：">
                <el-radio-group v-model="form.auditResult" @change="auditResultChange">
                    <el-radio :label="1">通过</el-radio>
                    <el-radio :label="2">拒绝</el-radio>
                </el-radio-group>
            </el-form-item>
            <template v-if="form.auditResult == 1">
                <el-form-item label="打款方式：">{{ form.transferTypeName }}</el-form-item>
                <el-form-item v-if="form.transferType == 1" label="打款凭证：" prop="transferReceipt">
                    <ImgUpload
                        ref="receiptImgRef"
                        v-model="form.transferReceipt"
                        :is-change="true"
                        accept="image/png,image/jpeg,image/jpg"
                        :currentImg="getCurrentImg(form.transferReceipt)"
                        @imgStateChange="imgStateChange"
                        tip-content="请确保线下已打款成功，再上传图片。"
                /></el-form-item>
            </template>
            <template v-else>
                <el-form-item label="拒绝原因：" prop="rejectReason">
                    <el-input
                        class="w300"
                        type="textarea"
                        :rows="4"
                        v-model="form.rejectReason"
                        show-word-limit
                        maxlength="500"
                        resize="none"
                        placeholder="请填写拒绝原因"
                        autocomplete="off"></el-input>
                </el-form-item>
            </template>
        </el-form>
        <template #footer>
            <div style="flex: auto">
                <el-button plain @click="handleVisible(false)">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确认</el-button>
            </div>
        </template>
    </el-dialog>
    <RechargeDia ref="rechargeDiaRef" v-model="rechargeVisible"></RechargeDia>
</template>

<script setup>
import { reactive, ref, unref, computed } from 'vue';
import request from '@/request/index';
import { cloneDeep } from '@/commons/utils.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import ImgUpload from '@/components/ImageUpload.vue';
import RechargeDia from '@/views/sys/pay/account/rechargeDia.vue';

const emit = defineEmits(['closed', 'confirm']);

const formRef = ref();
const receiptImgRef = ref();
const rechargeDiaRef = ref();
let rechargeVisible = ref(false);
let form = reactive({
    id: null,
    sn: '',
    nickName: '',
    realName: '',
    idNo: '',
    mobile: '',
    withdrawTo: null,
    withdrawToName: '',
    bankName: '',
    bankAccountNo: '',
    auditStatus: null,
    auditStatusName: '',
    failedReason: '',
    rejectReason: '',
    auditAt: '',
    createdAt: '',
    amount: '',
    auditResult: 1,
    auditResultName: '',
    transferType: null, //打款方式：1-线下打款 2-微信 3-宝付账户
    transferTypeName: '',
    transferReceipt: ''
});
let formClone = cloneDeep(form);
let dialogVisible = ref(false);
const rules = {
    rejectReason: [{ required: true, message: '请填写拒绝原因', trigger: 'blur' }],
    transferReceipt: [{ required: true, message: '请上传打款凭证', trigger: 'blur' }]
};

let isAuthorized = ref(false);
// const transferTypeName = computed(() => {
//     if (form.withdrawTo == 1) {
//         return '微信商家转账到零钱';
//     }
//     if (form.withdrawTo == 2) {
//         // 商家是否开通【委托授权】
//         if (isAuthorized.value) {
//             return '宝付账户自动扣款';
//         } else {
//             return '商家线下转账';
//         }
//     }
//     return '-';
// });

const clearValidate = field => {
    unref(formRef).clearValidate(field);
};

const validateField = field => {
    unref(formRef).validateField(field);
};

const auditResultChange = () => {
    form.rejectReason = '';
    form.transferReceipt = '';
};

const getCurrentImg = (val, imgSrc) => {
    if (val?.[0]?.response?.data?.url) {
        return val?.[0]?.response?.data?.url;
    }
    return val || null;
};

const setImgSrcObject = img => {
    if (img?.[0]?.response?.data?.url) {
        return img?.[0]?.response?.data?.url;
    }
    if (!img) {
        return '';
    }
    return img;
};

const imgStateChange = ({ msg }) => {
    if (['上传图片只能是jpg、png、jpeg格式！'].includes(msg)) {
        ElMessage({
            type: 'error',
            message: '上传图片只能是jpg、png、jpeg格式！'
        });
    }
    setTimeout(() => {
        validateField('transferReceipt');
    });
};

const hasAuthorized = async () => {
    const { data } = await request('withdrawSettingInfo');
    isAuthorized.value = data?.baofooAutoTransfer;
};
const openDialog = async row => {
    const { data } = await request('withdrawInfo', { id: row.id });
    const _data = cloneDeep(data);
    _data.auditResult = _data.auditResult || 1;
    Object.assign(form, _data);
    if (_data.withdrawTo == 2) {
        hasAuthorized();
    }
    handleVisible(true);
};
const closedCallback = () => {
    Object.assign(form, cloneDeep(formClone));
    formRef.value.resetFields();
};
const handleVisible = (visible = false) => {
    dialogVisible.value = visible;
    if (!visible) {
        emit('closed');
    }
};
const handleConfirm = async () => {
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            if (receiptImgRef.value && receiptImgRef.value.loading) {
                return ElMessage({
                    type: 'error',
                    message: '图片正在上传中...，请稍后保存'
                });
            }
            // todo:setImgSrcObject
            try {
                const _form = cloneDeep(form);
                _form.transferReceipt = setImgSrcObject(_form.transferReceipt);
                // if (form.auditResult == 1) {
                //     if (form.withdrawTo == 1) {
                //         // 微信
                //         _form.transferType = 2;
                //     } else if (form.withdrawTo == 2) {
                //         // 商家是否开通【委托授权】
                //         if (isAuthorized.value) {
                //             // 宝付
                //             _form.transferType = 3;
                //         } else {
                //             // 线下
                //             _form.transferType = 1;
                //         }
                //     }
                // }
                const { id, auditResult, rejectReason, transferType, transferReceipt } = _form;
                const params = { id, auditResult, rejectReason, transferType, transferReceipt };
                // todo:注释请求
                const { code, msg } = await request('withdrawAudit', params);
                // const code = 3;
                // const msg = '';
                if (code !== 0) {
                    // const msgs = {
                    //     9002101: '账户余额不足，请先充值',
                    //     9002102: '微信运营账户不足，请先充值',
                    //     9002103: '该用户已达每日提现上限，请明天再来审核~',
                    //     9002104: '微信账户今日已达转账额度，请明天再来审核~',
                    //     9002105: '已超过单笔转账上限'
                    // };
                    let confirmButtonText = '好的';
                    const isTopUp = [9002101, 9002102].includes(code / 1);
                    if (isTopUp) {
                        confirmButtonText = '立即充值';
                    }
                    ElMessageBox.alert(msg, '提示', {
                        confirmButtonText,
                        center: true,
                        customClass: 'custom-message-class',
                        callback: action => {
                            if (action !== 'confirm') {
                                return;
                            }
                            if (isTopUp) {
                                if (code == 9002101) {
                                    // 续费弹窗
                                    rechargeVisible.value = true;
                                } else {
                                    window.open(
                                        'https://pay.weixin.qq.com/index.php/core/home/login?return_url=' +
                                            window.location.href,
                                        '_blank'
                                    );
                                }
                            }
                            // handleVisible();
                        }
                    });
                    return;
                }
                ElMessage({
                    type: 'success',
                    message: '操作成功'
                });
                // todo:emit 关闭窗口重置
                emit('confirm');
                handleVisible();
            } catch (error) {
                ElMessage({
                    type: 'error',
                    message: error?.msg || '系统异常'
                });
            }
        } else {
            unref(formRef).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

defineExpose({
    openDialog
});
</script>

<style lang="scss">
.withdraw-audit-dialog {
    max-width: 700px;
    min-width: 700px;
    .el-dialog__body {
        padding-left: 34px !important;
        max-height: 600px;
        overflow-y: auto;
    }
    .el-form-item {
        margin-bottom: 8px;
    }
    .img-uploader {
        .el-upload {
            width: 80px;
            height: 80px;
            display: flex;
        }
        .img-uploader-icon,
        .has-upload-img {
            width: 80px !important;
            height: 80px !important;
        }
        .tip-icon {
            display: none;
        }
        /* .upload-tip {
            line-height: initial;
        } */
    }
}
.custom-message-class {
    width: 300px;
    .el-message-box__title {
        justify-content: flex-start;
    }
    .el-message-box__content {
        padding-top: 20px;
        padding-bottom: 20px;
        text-align: left;
    }
    .el-message-box__btns {
        .el-button {
            width: 200px;
            margin-bottom: 10px;
        }
    }
}
</style>
<style lang="scss" scoped>
.withdraw-audit-dialog {
    h1 {
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #33302d;
        position: relative;
        margin: 0;
        padding: 0;
        margin-bottom: 17px;
        &:not(:first-of-type) {
            margin-top: 23px;
        }
        &::before {
            position: absolute;
            content: '';
            left: -10px;
            width: 4px;
            height: 16px;
            background: #ff6b00;
            top: 50%;
            transform: translateY(-50%);
        }
    }
    .w300 {
        width: 400px;
    }
}
</style>
